package com.itbaizhan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OrmTest01 {
    public List<Users> selectAll(){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        //定义集合
        List<Users> list = new ArrayList<>();
        try{
            //获取Connection 对象  连接sql
            connection = JdbcUtils.getConnection();
            // 获取PreparedStatement 对象  编译sql语句
            ps = connection.prepareStatement("Select * from users");
            //获取结果集
            resultSet = ps.executeQuery();
            while (resultSet.next()){
               int userid = resultSet.getInt("userid");
               String username = resultSet.getString("username");
               int usetage =  resultSet.getInt("userage");
                //因为要数据有多条，所以要在循环里实例化实体对象，如果只有一条数据可以在循环外实例化
                Users users = new Users();
                users.setUserid(userid);
                users.setUsername(username);
                users.setUsergae(usetage);
                //把每次得到的对象放到集合中保存
                list.add(users);

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(resultSet,ps,connection);
        }
        return list;
    }
}
